package com.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public final class IOUtils {

	private static final int DEFAULT_BUFFER_SIZE = 1024;

	private IOUtils() {
	}

	public static void saveStreamToFile(InputStream inputStream, String fileName) throws IOException {
		File file = new File(fileName);

		OutputStream out = new FileOutputStream(file);

		int read = 0;
		byte[] bytes = new byte[DEFAULT_BUFFER_SIZE];

		while ((read = inputStream.read(bytes)) != -1) {
			out.write(bytes, 0, read);
		}

		inputStream.close();
		out.flush();
		out.close();
	}

	public static void saveStringToFile(String str, String fileName) {

		File file = getFileCreatingFolders(fileName);

		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(file));
			writer.write(str);
			writer.close();

		} catch (IOException e) {
			throw new IllegalStateException(String.format("Couldn't save str '%s' to file %s", str, fileName), e);
		}
	}

	public static File getFileCreatingFolders(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			String[] split = fileName.split("/");
			String path = fileName.replace(split[split.length - 1], "");
			new File(path).mkdirs();
			file = new File(fileName);
		}
		return file;
	}
}
